#include "qt_test.h"
#include <qtablewidget.h>
#include <qitemdelegate.h>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <qspinbox.h>
#include "transact.h"
#include "ConfigInfo.h"
#include <sql_Connector.h> // Strange, cannot include it in the qt_test.h file

#include "stdafx.h"
#include "SerialPort.h"

extern size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream);
qt_test::qt_test(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	Initialize();
	initializeStockDisplay(stockDisplay_current);
//	connect(ui.SearchButton, SIGNAL(clicked()), this, SLOT(on_SearchButton_clicked()));
//	connect(ui.ReStockButton, SIGNAL(clicked()), this, SLOT(on_ReStockButton_clicked()));
}


/*
	Do any intialization here
*/
void qt_test::Initialize()
{
	ui.transact_result->setText("");
	ui.PID_result_label->setText("");
	ui.PID_result_label->setWordWrap(true);
	ui.mainTab->setCurrentIndex(0);
	mthread = new MyThread();
	mthread->name="qt_Thread";
	//QObject::connect(mthread,SIGNAL(NumberChanged(int)), this, SLOT(onNumberChanged(int)));

	// Map the argument to be sent
	signalMapper =new QSignalMapper(this);
	QString PID=ui.pId_line_edit->text();
	signalMapper->setMapping(ui.sendPID_button,PID);
	QObject::connect(ui.sendPID_button,SIGNAL(clicked()),signalMapper,SLOT(map()));
	
	QObject::connect(signalMapper, SIGNAL(mapped(QString)),mthread, SLOT(sendPID(QString)));
	mthread->start();
	//Declare to run concurent like this
	/*QFuture<void> future= QtConcurrent::run(this, &qt_test::transact_by_Curdate_c);
	future.waitForFinished();*/
	future=NULL;
	watcher=NULL;
	QObject::connect(ui.reStockID_search,SIGNAL(editingFinished()), this, SLOT(findRestockId()));
	QObject::connect(ui.pId_line_edit,SIGNAL(editingFinished()), this, SLOT(pId_line_edit_editing_Finished()));
	QObject::connect(ui.barcode_transact_find, SIGNAL(editingFinished()), this, SLOT(findTransactID()));
	QObject::connect(this, SIGNAL(new_info(void)), mthread, SLOT(pid_new_info(void)));
}

void qt_test::findTransactID()
{
	string value=ui.barcode_transact_find->text().toStdString();
	
	int j,l=value.length();
	// Check syntax
	if (!is_number(value))
		return;

	int valueI=boost::lexical_cast<int>(value);
	int barcodeI;
	string barcode;
	int numRows=ui.consolidate_tab->rowCount();
	int i;
	for (i=0;i<numRows;i++)
	{
		barcode=ui.consolidate_tab->item(i,0)->text().toStdString();
		barcodeI=boost::lexical_cast<int>(barcode);
		if (valueI==barcodeI)
		{
			ui.consolidate_tab->selectRow(i);
			break;
		}
	}
}

qt_test::~qt_test()
{
	if (future!=NULL)
		delete future;
	if (watcher!=NULL)
		delete watcher;
	delete signalMapper;
	delete mthread;
}

void qt_test::on_newDay_clicked()
{
	/*ui.textEdit->setText("hello world!");
	//Open a web url from browser
	QString link = "http://localhost/phpmyadmin/";
	QDesktopServices::openUrl(QUrl(link));*/
	sql_Connector *contor=new sql_Connector();
	contor->start_Connect();
	contor->chooseDB(LOCAL_DB);
	string curDate=contor->getCurdate();
	string filename= "Inventory_"+ boost::lexical_cast<string>(SHOP_ID)+"_"+curDate+".txt";
	stockDisplay_current.clear();
	contor->clearItem();
	contor->insert_from_FILE(filename);
	contor->clearPriceDisplay();
	contor->map_PriceDisplay();
	initializeStockDisplay(stockDisplay_current);
	ui.textEdit->setText("Load stock complete! Have a nice day !");
	
	delete contor;
}


void qt_test::clearTable(QTableWidget *table) {
	table->setRowCount(0);
	return;
}

/*
	When the button is clicked, take the barcode value from the barcode_line and search the item based on that barcode
*/
void qt_test::on_SearchButton_clicked()
{
	int j=0;
	clearTable(ui.item_table);
	QString label_result="Empty Result!";
	QString barcode=ui.barcode_line->text();
	QString iName=ui.name_line->text();
	QString iCate=ui.cate_line->text();
	QString iManu=ui.manu_line->text();
	string barcod=barcode.toStdString();
	string iNam=iName.toStdString();
	string iCat=iCate.toStdString();
	string iMan=iManu.toStdString();
	vector<Item*> iList;
	ui.result_label->setStyleSheet("QLabel { color : red; font: bold 14px; }");
	if (barcod.length()<=BARCODE_LENGTH)
	{
		//Item *tmp=new Item();
		Item *tmp;
		// Set up sql_connector to access database
		sql_Connector *contor=new sql_Connector();
		contor->start_Connect();
		contor->chooseDB("CG3002");
		//if (contor->search_from_barcode( atoi(barcod.c_str()),tmp)==1)
		if (contor->search_general(barcod,iNam,iCat,iMan,iList))
		{
			int size=iList.size();
			for (int i=0;i<size;i++)
			{
				QString val;
				ui.item_table->insertRow(j);
				ui.item_table->setSortingEnabled(false);
				QTableWidgetItem *item1;
				tmp=iList[i];
				for (int z=0; z < 8; z++)
				{
					switch(z)
					{
					case colItemID:
						//Fill in item Id;
						val= QString::fromStdString(tmp->get_ItemID_toStr());
						break;
					case colItemName:
						//Fill in item_name;
						val= QString::fromStdString(tmp->get_ItemName());
						break;
					case colItemCat:
						//Fill in category;
						val = QString::fromStdString(tmp->get_ItemCategory());
						break;
					case colItemManu:
						//Fill in manufacturer:
						val = QString::fromStdString(tmp->get_ItemManufacturer());
						break;
					case colItemPrice:
						//Fill in price;
						val = QString::fromStdString(tmp->get_ItemPrice_toStr());
						break;
					case colItemLocalStock:
						//Fill in local stock;
						val = QString::fromStdString(tmp->get_ItemLocalStock_toStr());
						break;
					case colItemMinStock:
						//Fill in minimum stock;
						val = QString::fromStdString(tmp->get_ItemMinStock_toStr());
						break;
					case colItemBundleUnit:
						//Fill in bundle
						val = QString::fromStdString(tmp->get_ItemBundelUnit_toStr());
						break;
					}
					//ui.item_table->setRowCount(j);
					ui.item_table->setItem(j,z,new QTableWidgetItem(val));
				}
				delete tmp;
			}
			iList.clear();
			
			ostringstream convert;   // stream used for the conversion
			convert << size;      // insert the textual representation of 'Number' in the characters in the stream
			ui.result_label->setStyleSheet("QLabel { color : green; font: bold 14px; }");
			label_result= QString::fromStdString(convert.str()) + " results";
		}
		delete contor;
	}
	ui.result_label->setText(label_result);
}

/*
	Sync the transactions, sort by the current chosen tab and output the results
*/
void qt_test::on_sync_button_clicked()
{
	// Get the current tab
	int cur_tab=ui.transact_table->currentIndex();
	string filename;
	
	switch (cur_tab)
	{
	case 0:	// Sorting by today
		transact_by_Curdate(filename);
		break;
	case 1:
		transact_by_Curdate_Consolidate(filename);
		break;
	}
	
}

/*
	Generate the report based on the chosen order
*/
void qt_test::on_transact_generate_Report_clicked()
{
	// Get the current tab
	int cur_tab=ui.transact_table->currentIndex();
	string filename;
	ostringstream res;
	string result;
	switch (cur_tab)
	{
	case 0:	// Sorting by today
		res=transact_by_Curdate(filename);
		result=res.str();
		break;
	case 1: // Sorting by today, consolidate
		res=transact_by_Curdate_Consolidate(filename);
		result=res.str();
		break;
	}
	// Save to file
	ofstream myfile (filename+".txt");
	myfile<<result;
	myfile.close();

	//Display the result
	ui.transact_result->setStyleSheet("QLabel { color : green; font: bold 12px; }");
	string gen_res= "Report name: " + filename +".txt genereated";
	ui.transact_result->setText(QString::fromStdString(gen_res));
	ui.transact_file->setText(QString::fromStdString(filename) + ".txt");
}

/*
	Populate the table with today transaction
	Return the ostring of all the transactions info incase need to write to file
	the filename is in the argument
*/
ostringstream qt_test::transact_by_Curdate(string &filename)
{
	QMutex mutex;
		mutex.lock();
	ostringstream result;
	int j = ui.transact_report->rowCount();
	if (j>0)
	{
		for (int i=0;i<j;i++)
			ui.transact_report->removeRow(0);
		j=0;
	}
	vector<Transaction *> iList;
	Transaction *tmp;
	int size,i;
	double revenue;
	// Set up sql_connector to access database
	sql_Connector *contor=new sql_Connector();
	contor->start_Connect();
	contor->chooseDB("CG3002");
	contor->get_Curdate_Transaction(iList);
	size=iList.size();
	filename="Transaction_"+boost::lexical_cast<string>(SHOP_ID)+"_";
	string date;
	for (i=0;i<size;i++)
	{
		QString val;
		ostringstream convert;
		ui.transact_report->insertRow(j);
		ui.transact_report->setSortingEnabled(false);
		QTableWidgetItem *item1;
		tmp=iList[i];
		for (int z=0;z<5;z++)
		{
			switch(z)
			{
			case 0:
				val= QString::fromStdString(tmp->get_tId_toStr());
				break;
			case 1:
				val= QString::fromStdString(tmp->get_cId_toStr());
				break;
			case 2:
				val= QString::fromStdString(tmp->get_iId_toStr());
				break;
			case 3:
				val= QString::fromStdString(tmp->get_Quantity_toStr());
				break;
			/*case 4:
				revenue=tmp->get_Price()*tmp->get_Quantity();
				convert << revenue;
				val = QString::fromStdString(convert.str());
				break;*/
			case 4:
				val = QString::fromStdString(tmp->get_Date());
				date=tmp->get_Date();
				break;
			}
			//ui.item_table->setRowCount(j);
			ui.transact_report->setItem(j,z,new QTableWidgetItem(val));
			result<< val.toStdString();
			if (z<4)
				result<<":";
			else
				result<<"\n";
		}
		delete tmp;
	}
	
	filename+=date;
	ui.transact_result->setStyleSheet("QLabel { color : green; font: bold 12px; }");
	string trans_res="Sync complete, " + convert_from_int(size) + " results found";
	ui.transact_result->setText(QString::fromStdString(trans_res));
	iList.clear();
	delete contor;

	mutex.unlock();
	return result;
}

string qt_test::convert_from_int(int toCon)
{
	ostringstream convert;
	convert<<toCon;
	return convert.str();
}

/*
	Open a transaction file
*/
void qt_test::on_transact_open_file_clicked()
{
	QString filename;
	filename=QFileDialog::getOpenFileName();
	QString f = QFileInfo(filename).fileName();
	ui.transact_file->setText(f);
}

/*
	Sending file chosen to HQ
*/
void qt_test::on_transact_send_clicked()
{
	string filename;
	future = new QFuture<void>;
	watcher =new QFutureWatcher<void>;
	QObject::connect(watcher,SIGNAL(finished()),this, SLOT(sendFinish()));
	filename=ui.transact_file->text().toStdString();
	*future = QtConcurrent::run(this,&qt_test::upload,filename);
	watcher->setFuture(*future);
	//upload(filename);
}


void qt_test::upload(string filename)
{
	CURL *curl;
  CURLcode res;

  struct curl_httppost *formpost=NULL;
  struct curl_httppost *lastptr=NULL;
  struct curl_slist *headerlist=NULL;
  static const char buf[] = "Expect:";

  curl_global_init(CURL_GLOBAL_ALL);

  /* Fill in the file upload field */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "sendfile",
			   CURLFORM_FILE, filename.c_str(),
               CURLFORM_END);

  /* Fill in the filename field */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "filename",
			   CURLFORM_COPYCONTENTS, filename.c_str(),
               CURLFORM_END);


  /* Fill in the submit field too, even if this is rarely needed */
  curl_formadd(&formpost,
               &lastptr,
               CURLFORM_COPYNAME, "submit",
               CURLFORM_COPYCONTENTS, "send",
               CURLFORM_END);

  curl = curl_easy_init();
  /* initalize custom header list (stating that Expect: 100-continue is not
     wanted */
  headerlist = curl_slist_append(headerlist, buf);
  if(curl) {
    /* what URL that receives this POST */
    curl_easy_setopt(curl, CURLOPT_URL, DST_URL);

    /* enable verbose for easier tracing */
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
      curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
    curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);


    res = curl_easy_perform(curl);

    /* always cleanup */
    curl_easy_cleanup(curl);

    /* then cleanup the formpost chain */
    curl_formfree(formpost);
    /* free slist */
    curl_slist_free_all (headerlist);
  }
}

void qt_test::sendFinish()
{
	ui.transact_result->setStyleSheet("QLabel { color : green; font: bold 12px; }");
	ui.transact_result->setText("sending complete");
	delete future;
	
	delete watcher;
	future=NULL;
	watcher=NULL;
}

/*
	Function to generate Consolidate Report
*/
ostringstream qt_test::transact_by_Curdate_Consolidate(string &filename)
{
		ostringstream result;
		
	int j = ui.consolidate_tab->rowCount();
	if (j>0)
	{
		for (int i=0;i<j;i++)
			ui.consolidate_tab->removeRow(0);
		j=0;
	}
	vector<Transaction *> iList;
	Transaction *tmp;
	int size,i;
	double revenue;
	// Set up sql_connector to access database
	sql_Connector *contor=new sql_Connector();
	contor->start_Connect();
	contor->chooseDB("CG3002");
	contor->get_Curdate_Transaction_Consolidate(iList);
	size=iList.size();
	filename="Transaction_"+boost::lexical_cast<string>(SHOP_ID)+"_";
	string date;
	for (i=0;i<size;i++)
	{
		QString val;
		ostringstream convert;
		ui.consolidate_tab->insertRow(j);
		ui.consolidate_tab->setSortingEnabled(false);
		QTableWidgetItem *item1;
		tmp=iList[i];
		for (int z=0;z<3;z++)
		{
			switch(z)
			{
			case 0:
				val= QString::fromStdString(tmp->get_iId_toStr());
				break;
			case 1:
				val= QString::fromStdString(tmp->get_Quantity_toStr());
				break;
			case 2:
				val = QString::fromStdString(tmp->get_Date());
				date=tmp->get_Date();
				break;
			}
			//ui.item_table->setRowCount(j);
			ui.consolidate_tab->setItem(j,z,new QTableWidgetItem(val));
			result<< val.toStdString();
			if (z<2)
				result<<':';
			else
				result<<"\r\n";
		}

		delete tmp;
	}
	filename+=date;
	ui.transact_result->setStyleSheet("QLabel { color : green; font: bold 12px; }");
	string trans_res="Sync complete, " + convert_from_int(size) + " results found";
	ui.transact_result->setText(QString::fromStdString(trans_res));
	iList.clear();
	delete contor;

	return result;
}

/*
	Slot to handle report
*/
void qt_test::onNumberChanged(int Number)
{
	ui.textEdit->setText(QString::number(Number));
}

/*size_t qt_test::write_data(void *ptr, size_t size, size_t nmemb, FILE *stream)
{
	size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}*/
void qt_test::on_GetfromHQ_clicked()
{
	CURL *curl;
    FILE *fp;
    CURLcode res;
	sql_Connector *contor=new sql_Connector();
	contor->start_Connect();
	contor->chooseDB(LOCAL_DB);
	string curDate=contor->getCurdate();
	string filename= "Inventory_"+ boost::lexical_cast<string>(SHOP_ID)+"_"+curDate+".txt";
	string Durl="http://cg3002-05-z.comp.nus.edu.sg/admin-panel/downloads/"+filename;
	delete contor;
	char *url=new char[Durl.length()+1];
	url[Durl.length()]='\0';
	strcpy(url,Durl.c_str());
	char *outfilename=new char[filename.length()+1];
	outfilename[filename.length()+1]='\0';

	strcpy(outfilename,filename.c_str());

    //char outfilename[FILENAME_MAX] = "testTakefile.txt";
    curl = curl_easy_init();
    if (curl) {
        fopen_s(&fp,outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
        curl_easy_cleanup(curl);
        fclose(fp);
		ui.textEdit->setText("get file complete");
    }
}

vector<string> qt_test::tokenizeString(const string &s, const string &sep) {
	vector<string> result;
	boost::char_separator<char> separator(sep.c_str());
	typedef boost::tokenizer< boost::char_separator<char> > t_tokenizer;
	t_tokenizer tok(s, separator);
	for (t_tokenizer::iterator beg = tok.begin(); beg != tok.end(); ++beg)
		result.push_back(*beg);
	return result;
}

void qt_test::initializeStockDisplay(vector<vector<string>> &stockDisplay_current) {
	vector<Item*> iList;
	reStockAmount.clear();
	sql_Connector *contor = new sql_Connector(LOCAL_SERVER, LOCAL_USR, LOCAL_PWD);
	assert(contor != NULL);
	contor->start_Connect(LOCAL_DB);
	if (!contor->searchGeneralStockExceedsMinStock("", "", "", "", iList) ) {
		delete contor;
		iList.clear();
		return;
	}

	for (int i = 0; i < iList.size(); i++ ) {
		assert(iList[i] != NULL);
		vector<string> curLine;
		for (int j = colItemID; j <= colItemBundleUnit; j++ ) {
			switch(j) {
			case colItemID:
				curLine.push_back(boost::lexical_cast<string>(iList[i]->get_ItemID()));
				break;
			case colItemName:
				curLine.push_back(boost::lexical_cast<string>(iList[i]->get_ItemName()));
				break;
			case colItemCat:
				curLine.push_back(boost::lexical_cast<string>(iList[i]->get_ItemCategory()));
				break;
			case colItemManu:
				curLine.push_back(boost::lexical_cast<string>(iList[i]->get_ItemManufacturer()));
				break;
			case colItemPrice:
				curLine.push_back(iList[i]->get_ItemPrice_toStr());
				break;
			case colItemLocalStock:
				curLine.push_back(boost::lexical_cast<string>(iList[i]->get_ItemLocalStock()));
				break;
			case colItemMinStock:
				curLine.push_back(boost::lexical_cast<string>(iList[i]->get_ItemMinStock()));
				break;
			case colItemBundleUnit:
				curLine.push_back(boost::lexical_cast<string>(iList[i]->get_ItemBundelUnit()));
				break;
			}	//end switch
		}	// end for j
		stockDisplay_current.push_back(curLine);
	}
	iList.clear();
	delete contor;
}

void qt_test::loadCurStockDisplay(const vector<vector<string>> &stockDisplay_current) {
	clearTable(ui.stockDisplay);

	for (int i = 0; i < stockDisplay_current.size(); i++) {
		if (i>=reStockAmount.size())
			reStockAmount.push_back("0");

		ui.stockDisplay->insertRow(i);
		ui.stockDisplay->setSortingEnabled(false);
		vector<string> curLine = stockDisplay_current[i];
		for (int j = reItemID; j <= reAmount; j++) 
		{
			int k;
			QTableWidgetItem *tableItem;
			if (j<colItemPrice)
				k=j;
			else
				k=j+1;
			if (k<7)
				tableItem = new QTableWidgetItem(QString::fromStdString(stockDisplay_current[i][k]));
			else
				tableItem = new QTableWidgetItem(QString::fromStdString(reStockAmount[i]));

			if (j == reAmount) {
				tableItem->setFlags(tableItem->flags() | Qt::ItemIsEditable);
			}
			else tableItem->setFlags(tableItem->flags() & ~Qt::ItemIsEditable & ~Qt::ItemIsSelectable & ~Qt::ItemIsEnabled);
			ui.stockDisplay->setItem(i, j, tableItem);
			QObject::connect(ui.stockDisplay, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(stockDisplay_localStockCellDoubleClicked(int, int)));
		}
	}
}

void qt_test::stockDisplay_localStockCellDoubleClicked(int row, int col) {
	//cout << row << " " << col << endl;
	assert(ui.stockDisplay->item(row,col) != NULL);
	assert(reStockAmount.size()>row);
	reStockAmount[row]=ui.stockDisplay->item(row,col)->text().toStdString();
	QObject::connect(ui.stockDisplay, SIGNAL(currentItemChanged(QTableWidgetItem *, QTableWidgetItem *)), this, SLOT(stockDisplay_localStockValueChanged(QTableWidgetItem *, QTableWidgetItem *)));
}


void qt_test::stockDisplay_localStockValueChanged(QTableWidgetItem * curItem, QTableWidgetItem * prevItem) {
	if (prevItem == NULL) return;
	assert(prevItem != NULL);
	//cout << prevItem -> text().toStdString() <<endl;
	stockDisplay_current[prevItem->row()][colItemLocalStock] = prevItem->text().toStdString();
}

void qt_test::on_mainTab_currentChanged(int index) {
	if (index != idxTabReStock) return;
	loadCurStockDisplay(stockDisplay_current);
	ui.restock_Result_label->setText("");
	return;
}

/**
	pre: vector<vector<string>> reflects the entire changes from user in runtime
	post: output to ReStock_1_DATE.txt in the following format Barcode:NewStock
**/
void qt_test::on_ReStockButton_clicked()
{
	sql_Connector *contor=new sql_Connector();
	contor->start_Connect();
	contor->chooseDB(LOCAL_DB);
	string date=contor->getCurdate();
	string filename=boost::lexical_cast<string>("ReStock_" + boost::lexical_cast<string>(SHOP_ID) + "_"+date +".txt").c_str();
	
	findRestockandSend(filename);
	//fclose(stdout);
	//cout << "ReStock-ed to File" << endl;
	
}

void qt_test::findRestockandSend(string filename)
{
	ofstream fout(filename, ios::out);
	bool flag=true;
	int size=reStockAmount.size();
	//freopen(boost::lexical_cast<string>("ReStock_" + boost::lexical_cast<string>(SHOP_ID) + "_DATE.txt").c_str(), "w", stdout);
	for (int i = 0; i < stockDisplay_current.size(); i++) 
	{
		assert(size>i);
		string restockAmount=ui.stockDisplay->item(i,reAmount)->text().toStdString();
		string EODstock=ui.stockDisplay->item(i,4)->text().toStdString();
		if (is_number(restockAmount))
		{
			reStockAmount[i]=restockAmount;
			int amount= boost::lexical_cast<int>(restockAmount);
			int EoDstock_int= boost::lexical_cast<int>(EODstock);
			if (amount)
				fout << stockDisplay_current[i][reItemID] << ":" <<EoDstock_int << ":" <<restockAmount << endl;
		}
		else
		{
			ui.restock_Result_label->setStyleSheet("QLabel { color : red; font: bold 14px; }");
			ui.restock_Result_label->setText(QString::fromStdString(("value in row ") + boost::lexical_cast<string>(i+1)+ " is not a number!"));
			ui.stockDisplay->selectRow(i);
			flag=false;
			break;
		}
	}
	fout.close();
	if (flag)
	{
		future = new QFuture<void>;
		watcher =new QFutureWatcher<void>;
		QObject::connect(watcher,SIGNAL(finished()),this, SLOT(sendFinish()));
		*future = QtConcurrent::run(this,&qt_test::upload,filename);
		watcher->setFuture(*future);
		ui.restock_Result_label->setStyleSheet("QLabel { color : green; font: bold 14px; }");
		ui.restock_Result_label->setText(QString::fromStdString("task finish!"));
	}

	return;
}

void qt_test::findRestockId()
{
	string value=ui.reStockID_search->text().toStdString();
	
	int j,l=value.length();
	// Check syntax
	if (!is_number(value))
		return;

	int valueI=boost::lexical_cast<int>(value);
	int barcodeI;
	string barcode;
	int numRows=ui.stockDisplay->rowCount();
	int i;
	for (i=0;i<numRows;i++)
	{
		barcode=ui.stockDisplay->item(i,0)->text().toStdString();
		barcodeI=boost::lexical_cast<int>(barcode);
		if (valueI==barcodeI)
		{
			ui.stockDisplay->selectRow(i);
			break;
		}
	}
}

bool qt_test::is_number(const std::string& s)
{
	return !s.empty() && std::find_if(s.begin(), 
        s.end(), [](char c) { return !isdigit(c); }) == s.end();
}

void qt_test::on_mTransact_button_clicked()
{
	transact *Itran= new transact(stockDisplay_current);
	// Prevent choosing another window
	Itran->setModal(true);
	//Fixed the window size:
	Itran->setFixedSize(TRANS_WIDTH,TRANS_HEIGHT);
	Itran->show();

}

void qt_test::pId_line_edit_editing_Finished()
{
	string pId=ui.pId_line_edit->text().toStdString();
	if (is_number(pId))
	{
		sql_Connector *contor=new sql_Connector();
		contor->start_Connect();
		contor->chooseDB(LOCAL_DB);
		string barcode=contor->search_from_pId(pId);
		ui.barcode_line_edit->setText(QString::fromStdString(barcode));
		// map the new thing
		QString PID=ui.pId_line_edit->text();
		signalMapper->setMapping(ui.sendPID_button,PID);
		delete contor;
	}
}

void qt_test::on_ClearPID_button_clicked()
{
	string pId=ui.pId_line_edit->text().toStdString();
	if (is_number(pId))
	{
		sql_Connector *contor=new sql_Connector();
		contor->start_Connect();
		contor->chooseDB(LOCAL_DB);
		contor->clear_PID(pId);
		ui.PID_result_label->setStyleSheet("QLabel { color : green; font: bold 14px; }");
		ui.PID_result_label->setText("Price Display Unit clear");
		delete contor;
	}
	else
	{
		ui.PID_result_label->setStyleSheet("QLabel { color : red; font: bold 14px; }");
		ui.PID_result_label->setText("Please enter correct  format for PID");
	}
}

void qt_test::on_MapPID_button_clicked()
{
	string new_Barcode=ui.newBarcode_pID->text().toStdString();
	Item *tmp=new Item();
	// check if barcode exists
	sql_Connector *contor=new sql_Connector();
	contor->start_Connect();
	contor->chooseDB(LOCAL_DB);
	if (is_number(new_Barcode) &&  contor->search_from_barcode(boost::lexical_cast<int>(new_Barcode),tmp))
	{
		contor->add_PID(ui.pId_line_edit->text().toStdString(),boost::lexical_cast<int>(new_Barcode));
		ui.PID_result_label->setStyleSheet("QLabel { color : green; font: bold 14px; }");
		ui.PID_result_label->setText("Complete map price display to new barcode");
	}
	else
	{
		ui.PID_result_label->setStyleSheet("QLabel { color : red; font: bold 14px; }");
		ui.PID_result_label->setText("That barcode is not allowed");
	}
	delete tmp;
	delete contor;
}

void qt_test::on_reset_transact_button_clicked()
{
	sql_Connector *contor=new sql_Connector();
	contor->start_Connect();
	contor->chooseDB(LOCAL_DB);
	contor->delete_cashiers();
	contor->insert_Transaction_from_FILE("Trans_1000_20_9_11759.txt");
	delete contor;
}

void qt_test::on_dy_price_button_clicked()
{
	sql_Connector *contor=new sql_Connector();
	contor->start_Connect();
	contor->chooseDB(LOCAL_DB);

	if (contor->dynamic_Pricing())
	{
		ui.PID_result_label->setStyleSheet("QLabel { color : green; font: bold 14px; }");
		ui.PID_result_label->setText("Complete updating new price");
		emit(new_info());
	}
	delete contor;
	
}
